package cn.admin.configcenter.configservice.service;

import cn.admin.configcenter.configservice.domain.ConfigInfo;
import cn.admin.configcenter.configservice.persist.ConfigBaseDAO;
import cn.admin.configcenter.configservice.service.event.Event;
import cn.admin.configcenter.configservice.service.event.EventDispatcher;
import cn.admin.configcenter.configservice.service.event.EventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConfigService implements EventListener {

	@Autowired
	private ConfigBaseDAO configPersistenceDao;

	public ConfigService() {
        EventDispatcher.addEventListener(this);
    }

	@Override
	public void onEvent(Event event) {

	}

	public String getConfigByDataIdAndGroupAndSrcIp(String dataId,String group,String srcIp) {
		ConfigInfo configInfo = null;
		try {
			configInfo = configPersistenceDao.getConfigByDataIdAndGroupAndSrcIp(dataId, group, srcIp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return configInfo == null ? null : configInfo.getContent();
	}

	public String getConfig(String dataId,String group) {
		ConfigInfo configInfo = null;

		try {
			configInfo = configPersistenceDao.getConfig(new ConfigInfo(dataId,group));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return configInfo == null ? null : configInfo.getContent();
	}

	public boolean createOrUpdateConfig(String dataId,String group,String content,String srcIp,
	                                    String appName) {
		ConfigInfo config = new ConfigInfo(dataId,group,content,srcIp,appName);
		return this.configPersistenceDao.createOrUpdateConfig(config);
	}

	public void removeConfig(String dataId,String group,String srcIp) {
		ConfigInfo config = new ConfigInfo(dataId,group,srcIp);
		this.configPersistenceDao.removeConfig(config);
	}

	public void removeConfig(String dataId,String group) {
	    ConfigInfo config = new ConfigInfo(dataId,group);
	    this.configPersistenceDao.removeConfig(config);
    }

	public void createConfig(ConfigInfo config) {
		this.configPersistenceDao.createConfig(config);
	}

}
